package com.lieve.tomcat;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@SpringBootApplication
public class TomcatApplication {

    public static volatile AtomicInteger count = new AtomicInteger();

    public static void main(String[] args) {
        SpringApplication.run(TomcatApplication.class, args);
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行 ShutdownHook ...");
            }
        }));
    }

    public static int count() {
        return count.incrementAndGet();
    }

    public static int getCount() {
        return count.intValue();
    }

    public static void reset() {
        count = new AtomicInteger(0);
    }


    @EnableScheduling
    @RestController
    @RequestMapping("/api")
    public class TestController {

        @Resource
        private ThreadPoolExectorService threadPoolExectorService;

        @GetMapping(value = "/echo")

        public String echo() throws InterruptedException {
            log.info("echo count : {}", count());
            return "OK";
        }


        @GetMapping(value = "/hello")
        public String hello() throws InterruptedException {
            log.info("hello count : {}", count());
            Thread.sleep(1000 * 2);
            return "OK";
        }

        @GetMapping(value = "/max")
        public Integer max() throws InterruptedException {
            return threadPoolExectorService.getMaxWorkTime();
        }


        // @Scheduled(fixedRate = 5000)
        public void schedule() {
            reset();
            log.info("reset : {}", getCount());
        }
    }

    @Bean
    public ThreadPoolTaskExecutor executor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(1000);
        executor.setKeepAliveSeconds(5);
        return executor;
    }
}
